package com.woniu.zsd.recycle.consumer;

import com.woniu.zsd.recycle.mapper.EvaluateMapper;
import com.woniu.zsd.recycle.mapper.RecyclingOrderMapper;
import com.woniu.zsd.recycle.model.Evaluate;
import com.woniu.zsd.recycle.model.RecyclingOrder;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Component
public class WaitingAppraiseConsumer {
    @Resource
    private RecyclingOrderMapper recyclingOrderMapper;
    @Resource
    private EvaluateMapper evaluateMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "appraise_queue"),
            exchange = @Exchange(name = "d1"),
            key = "waiting_appraise"
    ))
    @RabbitHandler
    public void waitingAppraise(String recyclingOrderNum) throws Exception{
        // 生成锁的键（基于订单号）
        String lockKey = "lock:waiting_appraise:" + recyclingOrderNum;
        // 尝试加锁（设置过期时间防止死锁）
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", 30, TimeUnit.SECONDS);


        if (locked != null && locked) {
            try {
                RecyclingOrder recyclingOrder = recyclingOrderMapper.selectById(recyclingOrderNum);
                //这段时间内，如果有人评价过，则不再评价，结束延迟
                if (recyclingOrder.getStatus() == 5){
                    return;
                }
                //否则自动好评
                recyclingOrder.setStatus(5);
                //新增评价记录,自动5分好评
                Evaluate evaluate = new Evaluate();
                evaluate.setUserId(recyclingOrder.getUserId());
                evaluate.setOrderNum(recyclingOrderNum);
                evaluate.setScore(new BigDecimal(5));
                evaluate.setEvaluateTime(LocalDateTime.now());
                evaluate.setStationId(recyclingOrder.getStationId());
                evaluate.setState(1);
                evaluateMapper.insert(evaluate);
                //更新订单状态
                recyclingOrder.setStatus(5);
                recyclingOrderMapper.updateById(recyclingOrder);
            } finally {
                // 释放锁
                redisTemplate.delete(lockKey);
            }
        } else {
            // 未获取到锁，可以选择重试或直接丢弃
            System.out.println("未能获取锁，订单号：" + recyclingOrderNum);
        }
    }
}
